package com.saascloud.core.pojo;

import com.saascloud.core.exception.ErrorCode;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Date;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/19 10:19
 * @Version: 1.0
 * @Description:
 */
@Data
public class R<T> {

    /**
     *
     **/
    public static final Integer SUCCESS_CODE = 0;

    /**
     *
     **/
    public static final Integer FAIL_CODE = -1;

    /**
     * 成功或者失败的code错误码
     **/
    @ApiModelProperty(name = "状态码")
    private Integer code = 200;

    /**
     * 成功时返回的数据，失败时返回具体的异常信息
     **/
    @ApiModelProperty(name = "结果")
    private T data;

    /**
     * 请求失败返回的提示信息，给前端进行页面展示的信息
     **/
    private String msg = "success";

    /**
     * 服务器当前时间
     **/
    private Date currentTime;

    public R() {
    }

    public R(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
        this.currentTime = new Date();
    }


    public R(Integer code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
        this.currentTime = new Date();
    }

    public R(Integer code, T data) {
        this.code = code;
        this.data = data;
        this.msg = msg;
        this.currentTime = new Date();
    }

    public R(T data) {
        this.code = 200;
        this.data = data;
        this.currentTime = new Date();
    }


    public static <T> R<T> success(T t) {
        R result = new R(0, t);
        return result;
    }

    public static <T> R<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> R<T> error(Integer code, String msg) {
        R result = new R(code, msg);
        return result;
    }

    public boolean successed() {
        return SUCCESS_CODE.equals(code);
    }


    @Override
    public String toString() {
        return "R{" +
                ", code='" + code + '\'' +
                ", data=" + data +
                ", msg=" + msg +
                ", currentTime=" + currentTime +
                '}';
    }
}
